package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"net/http"
	"os"

	"gitee.com/xuender/kits/cmd"
	"gitee.com/xuender/oils/base"
	"gitee.com/xuender/oils/logs"
)

// nolint: gochecknoglobals
var port = 8080

func ping(writer http.ResponseWriter, req *http.Request) {
	writer.Header().Set("Content-Type", "application/json; charset=utf-8")

	value := map[string]any{}

	value["Proto"] = req.Proto
	value["Host"] = req.Host
	value["URL"] = req.URL
	value["RemoteAddr"] = req.RemoteAddr
	value["Method"] = req.Method
	value["RequestURI"] = req.RequestURI
	value["Header"] = req.Header
	value["Cookies"] = req.Cookies()

	if req.Form != nil {
		value["Form"] = req.Form
	}

	if body, _ := io.ReadAll(req.Body); len(body) > 0 {
		value["Body"] = string(body)
	}

	if data, err := json.Marshal(value); err != nil {
		_, _ = io.WriteString(writer, err.Error())
	} else {
		_, _ = writer.Write(data)
	}
}

func main() {
	http.HandleFunc("/", ping)
	logs.Info("启动kit-ping")
	base.Panic(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}

// nolint: gochecknoinits
func init() {
	flag.Usage = usage
	flag.IntVar(&port, "port", port, "端口号")
	flag.Parse()
}

func usage() {
	fmt.Fprintf(flag.CommandLine.Output(), "kit-ping [%s]\n\n", cmd.ModVersion)
	fmt.Fprintf(flag.CommandLine.Output(), "显示Request详细信息\n\n")
	fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
	flag.PrintDefaults()
	fmt.Fprintf(flag.CommandLine.Output(), "\n模块: %s\n提交: %s\n", cmd.ModPath, cmd.ModSum)
}
